package com.cruise.game.common.config;

import com.cruise.game.common.constants.SecurityConstants;
import com.cruise.game.security.filter.JwtAuthenticationFilter;
import com.cruise.game.security.handler.AccessDeniedHandlerImpl;
import com.cruise.game.security.handler.AuthenticationEntryPointImpl;
import com.cruise.game.security.service.UserDetailsServiceImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * Spring Security配置类
 *
 * @author cruise
 * @date 2025-02-28
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Resource
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Resource
    private AccessDeniedHandlerImpl accessDeniedHandler;

    @Resource
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    /**
     * 密码编码器
     *
     * @return PasswordEncoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份验证管理器
     *
     * @return AuthenticationManager
     * @throws Exception 异常
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 配置身份验证管理器
     *
     * @param auth 身份验证管理器构建器
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * 配置HTTP安全
     *
     * @param http HTTP安全
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // 关闭CSRF
                .csrf().disable()
                // 不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 请求授权
                .authorizeRequests()
                // 允许对于网站静态资源的无授权访问
                .antMatchers(HttpMethod.GET,
                        "/",
                        "/*.html",
                        "/favicon.ico",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js",
                        "/swagger-resources/**",
                        "/v3/api-docs/**",
                        "/doc.html")
                .permitAll()
                // 对于获取token的和不需要登录的接口允许匿名访问
                .antMatchers(SecurityConstants.OPEN_API_URLS).permitAll()
                // 对于用户接口，需要用户角色
                .antMatchers(SecurityConstants.USER_API_URLS).hasAnyRole(
                        SecurityConstants.ROLE_USER.toUpperCase(),
                        SecurityConstants.ROLE_AGENT.toUpperCase(),
                        SecurityConstants.ROLE_ADMIN.toUpperCase())
                // 对于代理接口，需要代理角色
                .antMatchers(SecurityConstants.AGENT_API_URLS).hasAnyRole(
                        SecurityConstants.ROLE_AGENT.toUpperCase(),
                        SecurityConstants.ROLE_ADMIN.toUpperCase())
                // 对于管理员接口，需要管理员角色
                .antMatchers(SecurityConstants.ADMIN_API_URLS).hasRole(SecurityConstants.ROLE_ADMIN.toUpperCase())
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                // 添加JWT过滤器
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                // 添加自定义未授权和未登录结果返回
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(authenticationEntryPoint);

        // 禁用缓存
        http.headers().cacheControl();
    }
}
